/*
 * Copyright 2006-2023 ahtelit.com, All Rights Reserved.
 */

package com.telit.common.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * 非生产环境检查可发送短信的手机号
 *
 * @author yuezhuang
 * @since 2023-11-08
 */
@Component
@Slf4j
public class CheckSmsPhoneUtil {

    private static StringRedisTemplate redisTemplate;
    private static final String KEY_PHONE_WHITE_LIST = "phone_white";
    private static String CHECK_SMS_PHONE;

    @Autowired
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        CheckSmsPhoneUtil.redisTemplate = redisTemplate;
    }

    @Value("${forest.checkSmsPhone:false}")
    public void setEnv(String checkSmsPhone) {
        CHECK_SMS_PHONE = checkSmsPhone;
    }

    /**
     * 校验并返回可发送短信的手机号
     *
     * @param mobiles 待过滤的手机号
     *
     * @return 可发送短信的手机号
     */
    public static List<String> checkPhone(List<String> mobiles) {
        if ("true".equals(CHECK_SMS_PHONE)) {
            log.info("==============" + CHECK_SMS_PHONE);
            String s = redisTemplate.opsForValue().get(KEY_PHONE_WHITE_LIST);
            if (StrUtil.isEmpty(s)) {
                return null;
            }
            List<String> phoneWhiteList = new java.util.ArrayList<>(List.of(s.split(",")));
            mobiles.retainAll(phoneWhiteList);
            if (CollectionUtil.isEmpty(mobiles)) {
                return null;
            }
        }
        return mobiles;
    }

}
